#!/usr/bin/env python3
"""
自动化测试运行脚本
"""

import unittest
import sys
import os
import time
from datetime import datetime

def run_all_tests():
    """运行所有测试"""
    print("开始运行自动化测试...")
    start_time = time.time()
    
    # 添加项目根目录到 Python 路径
    project_root = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, project_root)
    
    # 创建输出目录
    os.makedirs("output", exist_ok=True)
    
    # 发现并运行测试
    loader = unittest.TestLoader()
    start_dir = os.path.join(project_root, "tests")
    suite = loader.discover(start_dir, pattern='test_*.py')
    
    # 运行测试
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)
    
    # 输出测试报告
    end_time = time.time()
    duration = end_time - start_time
    
    print("\n" + "="*60)
    print("测试执行报告")
    print("="*60)
    print(f"执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"运行时长: {duration:.2f}秒")
    print(f"测试用例数: {result.testsRun}")
    print(f"失败数: {len(result.failures)}")
    print(f"错误数: {len(result.errors)}")
    if result.testsRun > 0:
        print(f"通过率: {(result.testsRun - len(result.failures) - len(result.errors)) / result.testsRun * 100:.1f}%")
    else:
        print("通过率: 0.0%")
    
    # 输出失败详情
    if result.failures:
        print("\n失败用例详情:")
        for test, traceback in result.failures:
            print(f"  {test}: {traceback.splitlines()[-1]}")
    
    if result.errors:
        print("\n错误用例详情:")
        for test, traceback in result.errors:
            print(f"  {test}: {traceback.splitlines()[-1]}")
    
    # 返回退出码
    return 0 if result.wasSuccessful() else 1

if __name__ == "__main__":
    sys.exit(run_all_tests())